!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','status','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            common = layui.common;//自定义状态控件

        //定义总变量
        var AssistInfo = {
            tableId: "assistInfoTable",    //表格id
            menuType:{},                //类型
            condition: {                //查询条件
                name: "",
                type:"",
                startDate: "",
                endDate: ""
            },
            uploadImg : null    //上传封面base64吗
        }

        /****
         * 初始化获取帮助分类
         */
        AssistInfo.initType = function(){
            //异步请求获取字典项
            $.ajax({
                async: false,
                url: '/help/findHelpList',
                success: function (result) {
                    if (result && result.code == 200) {
                        //存储字典项
                        if( result.data && result.data.length>0  ){
                            $.each(result.data,function(key,obj){
                                //存储当前字典项
                                AssistInfo.menuType[obj.helpId] = obj.helpName;
                            });
                        }
                    }
                }
            });
            //渲染条件
            var html ='<option value="">全部</option>';
            $.each(AssistInfo.menuType,function(key,value){
                html += '<option value="'+key+'">'+value+'</option>';
            });
            $('#typeQuery').empty().append(html);
            form.render();
        }

        /**
         * 初始化列表列
         * **/
        AssistInfo.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'assistId', title: 'ID', width: 80,hide:true},
                {field: 'assistTitle', title: '帮助标题', width: 360},
                {field: 'helpId' ,title :'所属类别',width:320,templet:function(row){
                        return AssistInfo.menuType[row.helpId]==undefined?"":AssistInfo.menuType[row.helpId];
                    }},
                {field: 'createTime' ,title :'发布时间',width: 165, templet: function (row) {
                        return dateformat.format(row.createTime, 'yyyy-MM-dd hh:mm:ss');
                    }},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }


        /**
         * 查询方法
         * **/
        AssistInfo.search = function(){
            var queryData = {};
            queryData["name"] = $("#name").val();
            queryData["type"] = $("#typeQuery").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(AssistInfo.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        AssistInfo.addRecord =function (){
            window.location.href = "/assistInfo/add";
        }

        /**
         * 修改记录
         * **/
        AssistInfo.editRecord =function (data){
            window.location.href = "/assistInfo/update?id="+data.assistId;
        }

        /**
         * 查看记录
         * **/
        AssistInfo.detail =function (data){
            window.location.href = "/assistInfo/detail?id="+data.assistId;
        }

        /**
         * 删除记录
         * **/
        AssistInfo.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/assistInfo/delete?id=' + data.assistId,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        AssistInfo.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //初始化渲染列表
        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });

        AssistInfo.initType();

        table.render({
            elem:"#assistInfoTable"
            ,url:"/assistInfo/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:AssistInfo.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            AssistInfo.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            AssistInfo.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            AssistInfo.addRecord();
        });

        // 帮助分类点击事件
        $('#btnHelp').click(function () {
            window.location.href = "/help/list";
        });

        //普通图片上传
        var uploadFileBtn = upload.render({
            elem: '#uploadBtn'
            ,url: '/upload/uploadFiles'
            ,field:"layuiFiles"
            ,accept: 'file' //普通文件
            ,auto: false    //不自动上传
            ,exts: 'jpg|png|jpeg' //只允许上传压缩文件
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    var $uploadListDiv = $('#uploadListDiv');
                    var $tipUpload = $('#imgText');
                    var htmlDiv ='';
                    if(file.type.indexOf("image") !=-1){
                        if( (file.size/1014).toFixed(1) > 50 ){
                            return layer.msg("图片不能超过50kb");
                        }
                        uploadFileBtn.config.data ={"dir":"image"};
                        htmlDiv +='<img id="fileDiv" style="height: 137px;width: 137px;"/>';
                    }
                    $uploadListDiv.empty().append(htmlDiv);
                    //执行上传
                    obj.upload(index, file);
                });
            }
            ,done: function(res){
                if(res.code==1){
                    layer.alert(res.message,5);
                }
                if(res.error>0){
                    return layer.msg(res.message);
                }
                if(res.error==0){
                    var $uploadListDiv = $('#uploadListDiv');
                    $("#url").val(res.url);
                    $uploadListDiv.find("#fileDiv").attr("src",res.url);
                    layer.msg("上传成功");
                }
            }
        });

        //监听工具条
        table.on('tool(' + AssistInfo.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                AssistInfo.detail(data);
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该帮助吗？', function (index) {
                    AssistInfo.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                AssistInfo.editRecord(data);
                return false;
            }
        });
    });
}();